package connectfour;


import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.Transaction;
import javax.servlet.http.*;

import com.google.appengine.api.channel.ChannelService;
import com.google.appengine.api.channel.ChannelServiceFactory;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.labs.taskqueue.Queue;
import com.google.appengine.api.labs.taskqueue.QueueFactory;
import com.google.appengine.api.labs.taskqueue.TaskOptions;
import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.MemcacheServiceFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

@SuppressWarnings("serial")
public class JoinGameServlet extends HttpServlet {
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		UserService userService= UserServiceFactory.getUserService();
		User opponent = userService.getCurrentUser();
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		//MemcacheService mc = MemcacheServiceFactory.getMemcacheService();
		Player p; 
		/*
		// get player entity corresponding to this user
		Player p;
		if(mc.contains("player" + opponent.getUserId())){
			p = (Player)mc.get("player" + opponent.getUserId());
		}
		else{
			Query query = pm.newQuery(Player.class);
			query.declareImports("import com.google.appengine.api.users.User");
			query.setFilter("player == playerParam");
			query.setUnique(true);
			query.declareParameters("User playerParam");
			
			try {
				Player result = (Player) query.execute(opponent);
				if (result != null) {
					p = result;
				} else {
					p = new Player(opponent);
					pm.makePersistent(p);
					mc.put("player" + opponent.getUserId(), p);
				}
			} finally {
				query.closeAll();
			}
		}
		*/
		
		Query query = pm.newQuery(Player.class);
		query.declareImports("import com.google.appengine.api.users.User");
		query.setFilter("player == playerParam");
		query.setUnique(true);
		query.declareParameters("User playerParam");
		
		try {
			Player result = (Player) query.execute(opponent);
			if (result != null) {
				p = result;
			} else {
				p = new Player(opponent);
				pm.makePersistent(p);
				//mc.put("player" + opponent.getUserId(), p);
			}
		} finally {
			query.closeAll();
		}
		
		Game game;
		
		/*
		// get game entity to join (parameter of form)
		if(mc.contains("game" + req.getParameter("gameID"))){
			game = (Game) mc.get("game" + req.getParameter("gameID")); 
			
		}
		else{
			try {
				game = pm.getObjectById(Game.class, KeyFactory.createKey("Game", 
						Long.parseLong(req.getParameter("gameID"))));
	
			} finally {
			}
		}
		*/
		
		try {
			game = pm.getObjectById(Game.class, KeyFactory.createKey("Game", 
					Long.parseLong(req.getParameter("gameID"))));

		} finally {
		}
		
		// set attributes of p2 and game
		//p.setStatus(2); // opponent
		//p.setLastGamePlayed(game.getDate());
		//pm.makePersistent(p);
		
		game.setOpponent(p.getKey());
		game.setUserOpponent(opponent);
		game.incTurn();
		
		Transaction tx = pm.currentTransaction();
		Queue q = QueueFactory.getDefaultQueue();
		try{
			tx.begin();
			
			pm.makePersistent(game);
			
			TaskOptions t = TaskOptions.Builder.url("/persist").param("pKey", 
					KeyFactory.keyToString(p.getKey())).param("status", "2").param("wins", "0")
					.param("losses", "0").param("ratio", "0");
			q.add(t);
			
			tx.commit();
		}finally{
			if(tx.isActive()){
				tx.rollback();
			}
			pm.close();
		}
		
		// update memcache
		//mc.put("game" + game.getKey().getId(), game);

		
	    resp.sendRedirect("/game.jsp?gameID=" + game.getKey().getId());

	}
}
